<template>
  <div class="comment-post">
    <van-field
      class="post-field"
      v-model="message"
      rows="2"
      autosize
      type="textarea"
      maxlength="50"
      placeholder="请输入留言"
      show-word-limit
    />
    <van-button
      class='post-btn'
      @click="onPostComment"
      :disabled="!message.trim().length"
    >发布</van-button>
  </div>
</template>

<script>
// 导入发布文章评论的接口模块
import { addArticleComment } from '../../../api/comment.js'
export default {
  name: 'writeArticleComment',
  components: {},
  inject: {
    articleId: {
      type: [Number, String, Object],
      default: null
    }
  },
  props: {
    // 接收父组件传过来的文章id
    target: {
      type: [Number, String, Object],
      required: true
    },
    type: {
      type: String,
      // 自定义 Prop 数据验证,意思是只能传a或c
      validator (value) {
        return ['a', 'c'].includes(value)
      },
      // 默认值是a
      default: 'a'
    }

  },
  data () {
    return {
      message: ''
    }
  },
  computed: {},
  watch: {},
  created () { },
  mounted () { },
  methods: {
    // 发布文章评论的相关处理函数
    async onPostComment () {
      // 转圈圈的loading效果
      this.$toast.loading({
        message: '发布中...',
        forbidClick: true, // 禁用背景点击
        duration: 0 // 持续时间，默认 2000，0 表示持续展示不关闭
      })
      //  调接口
      try {
        const { data } = await addArticleComment({
          target: this.target.toString(), // 对文章评论是文章id 评论回复是评论id
          content: this.message,
          art_id: this.type === 'c' ? this.articleId.toString() : null// 对文章进行评论可以不写,文章评论a 评论回复c
        })
        console.log(data)
        // 把数据传递给父组件,完成页面的渲染
        this.$emit('onPostSuccess', data.data)
        // 清空发布文本框的值
        this.message = ''
        this.$toast.success('发布成功')
      } catch (error) {
        this.$toast.fail('发布失败!', error)
      }
    }
  }
}
</script>

<style scoped lang="less">
.comment-post {
  display: flex;
  align-items: center;
  padding: 32px 0 32px 32px;
  .post-field {
    background-color: #f5f7f9;
  }
  .post-btn {
    width: 150px;
    border: none;
    padding: 0;
    color: #6ba3d8;
    background: #fff;
    &::before {
      display: none;
    }
  }
}
</style>
